package com.zj.seckill.service;


import com.zj.seckill.dao.MiaoshaUserDao;
import com.zj.seckill.domain.MiaoshaUser;
import com.zj.seckill.exception.GlobalException;
import com.zj.seckill.redis.MiaoshaUserKey;
import com.zj.seckill.result.CodeMsg;
import com.zj.seckill.util.Md5Util;
import com.zj.seckill.util.RedisUtil;
import com.zj.seckill.util.UUIDUtil;
import com.zj.seckill.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
@Transactional
public class MiaoshaUserService {
	
	
	public static final String COOKI_NAME_TOKEN = "token";
	
	@Autowired
	MiaoshaUserDao miaoshaUserDao;

	@Autowired
	RedisUtil redisUtil;

	
	public MiaoshaUser getById(long id) {

		//取缓存
		MiaoshaUser user = redisUtil.get(MiaoshaUserKey.getById,""+id,MiaoshaUser.class);
		if (user != null){
			return user;
		}
		//取数据库
		user = miaoshaUserDao.getById(id);

		if (user != null){
			redisUtil.set(MiaoshaUserKey.getById,""+id,user);
		}

		return user;
	}


	public String login(HttpServletResponse response ,LoginVo loginVo) {
		if(loginVo == null) {
			throw new GlobalException(CodeMsg.SERVER_ERROR);
		}
		String mobile = loginVo.getMobile();
		String formPass = loginVo.getPassword();
		//判断手机号是否存在
		MiaoshaUser user = getById(Long.parseLong(mobile));
		if(user == null) {
			throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
		}
		//验证密码
		String dbPass = user.getPassword();
		String saltDB = user.getSalt();
		String calcPass = Md5Util.formPassToDBPass(formPass, saltDB);
		if(!calcPass.equals(dbPass)) {
			throw new GlobalException(CodeMsg.PASSWORD_ERROR);
		}
		//生成cookie
		String token = UUIDUtil.uuid();
		addCookie(response,token,user);
		return token;
	}


	public MiaoshaUser getByToken(String token,HttpServletResponse response) {
		if (StringUtils.isEmpty(token)){
			return null;
		}
		MiaoshaUser user = redisUtil.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
		//延长有效期
		if(user != null) {
			addCookie(response,token, user);
		}
		return user;
	}

	private void addCookie(HttpServletResponse response, String token,MiaoshaUser user) {
		redisUtil.set(MiaoshaUserKey.token, token, user);
		Cookie cookie = new Cookie(COOKI_NAME_TOKEN, token);
		cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
		cookie.setPath("/");
		response.addCookie(cookie);
	}
}
